package com.hyfd.task;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.hyfd.common.utils.DateTimeUtils;
import com.hyfd.common.utils.XmlUtils;
import com.hyfd.dao.mp.ProviderPhysicalChannelDao;
import com.hyfd.dao.mp.QianmiTokenDao;
import com.qianmi.open.api.response.TokenResponse;
import com.qianmi.open.api.tool.util.OAuthUtils;
import com.qianmi.open.api.tool.util.QianmiContext;

@Component
public class QianMiTokenTask {

	Logger log = Logger.getLogger(getClass());
	@Autowired
	ProviderPhysicalChannelDao providerPhysicalChannelDao;//物理通道信息
	@Autowired
	QianmiTokenDao qianmiTokenDao;//千米token信息
	
//	@Scheduled(cron="0 0 1 * * ?")//密钥更新时间待定
	public void getQianmiToken(){
		String id = "qianmiquanguoliuliang";//千米全国流量的通道id
		try{
			Map<String,Object> channel = providerPhysicalChannelDao.selectByPrimaryKey(id);
			String defaultParameter = (String) channel.get("default_parameter");//默认参数
			Map<String,String> paramMap = XmlUtils.readXmlToMap(defaultParameter);
			String appKey = paramMap.get("appKey");//
			String appSecret = paramMap.get("appSecret");//密钥
			String token = qianmiTokenDao.selectCurrentToken("1");//获取全国最新的token
			QianmiContext context = OAuthUtils.refreshToken(appKey, appSecret, token);
	        TokenResponse response = context.getTokenResponse();
	        if(response.isSuccess()){
	        	String updateDate = DateTimeUtils.formatDate(new Date(), "yyyy-MM-dd HH:mm:ss");
	        	String accessToken = response.getAccessToken();
	        	long expriesIn = response.getExpiresIn();//有效时间
	        	long endTime = System.currentTimeMillis() + expriesIn * 1000;//过期时间
	        	String endDate = DateTimeUtils.formatDate(new Date(endTime), "yyyy-MM-dd HH:mm:ss");//过期时间
	        	Map<String,Object> map = new HashMap<String,Object>();
	        	map.put("type", "1");//全国的token
	        	map.put("token", accessToken);
	        	map.put("updateDate", updateDate);
	        	map.put("endDate", endDate);
	        	qianmiTokenDao.insertSelective(map);//保存token
	        }else{
	        	log.error("千米获取token时 isSuccess不成功");
	        }
		}catch(Exception e){
			log.error("千米刷新token出错"+e.getMessage());
		}
	}
	
}
